package com.ruoyi.common.utils.file;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : zhenhc
 * @date : 2022-04-17 15:32
 **/
public class PomUtils {

    /**
     * 根据项目根路径获取所有pom文件的所有maven依赖,并按照从小到大排序
     * @param absolutePath 项目根路径
     * @return maven依赖
     */
    public static List<String> getDependencies(String absolutePath){
        //根据项目根路径过滤获取所有pom文件
        List<File> files = FileUtil.loopFiles(new File(absolutePath), file ->{
            String name = file.getName();
            List<String> split = StrUtil.split(name, ".");
            if ("pom".equals(split.get(0)))
                return true;
            else
                return false;
        });
        List<Map<String,String>> mapList = new ArrayList<>();
        //循环遍历获取xml标签dependency的所有子节点放在list集合里。
        files.forEach(file -> {
            String path = file.getAbsolutePath();
            Document document = XmlUtil.readXML(new File(path));
            NodeList nodeList = document.getElementsByTagName("dependency");
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node item = nodeList.item(i);
                NodeList childNodes = item.getChildNodes();
                Map<String, String> map = new HashMap<>();
                for (int j = 0; j < childNodes.getLength(); j++) {
                    if (childNodes.item(j).getNodeType() == Node.ELEMENT_NODE) {
                        //子标签名称
                        String nodeName = childNodes.item(j).getNodeName();
                        //子标签值
                        String nodeValue = childNodes.item(j).getFirstChild().getNodeValue();
                        map.put(nodeName, nodeValue);
                    }
                }
                mapList.add(map);
            }
        });
        //转换Map为String
        List<String> stringList = mapList.stream()
                .map(map -> map.get("groupId") + ":" + map.get("artifactId") + (map.containsKey("version") ? ":"+map.get("version") : ""))
                .collect(Collectors.toList());
        //排序
        List<String> sortList = stringList.stream().sorted(Comparator.comparing(String::toLowerCase))
                .collect(Collectors.toList());
        return sortList;
    }
}
